package com.scorpio.sdk.factory;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.Protocol;
import com.scorpio.common.utils.spring.SpringUtils;
import com.scorpio.sdk.constant.AliYunConstant;
import com.scorpio.system.service.ISysConfigService;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

public class OssClineFactory extends BasePooledObjectFactory<OSS> {


    //是否内网
    private boolean internal;

    public OssClineFactory(boolean internal) {
        this.internal = internal;
    }

    @Override
    public OSS create() {
        ISysConfigService configService = SpringUtils.getBean(ISysConfigService.class);
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setProtocol(Protocol.HTTPS);
        String endpoint;
        if (internal) {
            endpoint = configService.selectConfigByKey(AliYunConstant.ALIYUN_OSS_ENDPOINT_INTERNAL);
        } else {
            endpoint = configService.selectConfigByKey(AliYunConstant.ALIYUN_OSS_ENDPOINT);
        }
        String accessKeyId = configService.selectConfigByKey(AliYunConstant.ALIYUN_OSS_ACCESSKEYID);
        String accessKeySecret = configService.selectConfigByKey(AliYunConstant.ALIYUN_OSS_ACCESSKEYSECRET);
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    @Override
    public PooledObject<OSS> wrap(OSS oss) {
        return new DefaultPooledObject<>(oss);
    }

    @Override
    public void destroyObject(PooledObject<OSS> p) throws Exception {
        OSS oss = p.getObject();
        oss.shutdown();
        super.destroyObject(p);
    }
}
